package HomeWork.Util;

import java.sql.*;

public class GUIUtil {
    private static String qudong="com.mysql.cj.jdbc.Driver";
    private static String url="jdbc:mysql://127.0.0.1:3306/j180?serverTimezone=Asia/Shanghai";
    private static String zhanghao="root";
    private static String mima="994152993";
    private static Connection connection=null;
    private static PreparedStatement preparedStatement=null;
    private static ResultSet resultSet=null;
    private GUIUtil(){}
    public static Connection getConnection(){
        try {
            Class.forName(qudong);
            connection= DriverManager.getConnection(url,zhanghao,mima);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
    public static void close(){
        if(resultSet!=null){

            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(preparedStatement!=null){
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(connection!=null){

            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static int zengshangaicha(String sql,Object...pram){
        int num=0;
        getConnection();
        try {
            connection.setAutoCommit(false);
            preparedStatement=connection.prepareStatement(sql);
            if (pram!=null){
                for (int i = 0; i < pram.length; i++) {
                    preparedStatement.setObject(i+1,pram[i]);
                }
            }
            num=preparedStatement.executeUpdate();
            connection.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally {
            close();
        }
        return num;
    }
    public static ResultSet cha(String sql,Object...pram){
        try {
            getConnection();
            connection.setAutoCommit(false);
            preparedStatement=connection.prepareStatement(sql);
            if (pram!=null){
                for (int i = 0; i < pram.length; i++) {
                    preparedStatement.setObject(i+1,pram[i]);
                }
            }
            resultSet=preparedStatement.executeQuery();
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultSet;
    }

}
